package com.jinyang.baserouter.utils

import android.app.Activity
import android.content.Context
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentTransaction

/**
 * @Author:         LiuJinYang
 * @CreateDate:     2021/11/24
 * @Description:
 */
val permissionFragment: PermissionFragment = PermissionFragment()
fun requestMyPermissions(
    activity: FragmentActivity,
    permissions: Array<String>,
    callBack: (allGranted: Boolean) -> Unit
) {
    permissionFragment.permissions = permissions
    permissionFragment.callBack = callBack
    val fragmentTransaction = activity.supportFragmentManager.beginTransaction()
    if (permissionFragment.isAdded) {
        permissionFragment.removeFragment()
    }
    fragmentTransaction.add(permissionFragment, "permissionFragment@LJY").commit()
}

fun requestMyPermissions(permissions: Array<String>, callBack: (allGranted: Boolean) -> Unit) {
    val context: Activity = ApplicationUtil.instance.getTopActivity()
        ?: throw java.lang.NullPointerException("Top Activity is Null!")
    requestMyPermissions(context as FragmentActivity, permissions, callBack)
}

class PermissionFragment : Fragment() {
    private lateinit var requestMultiplePermissionsLauncher:
            ActivityResultLauncher<Array<String>>
    var permissions: Array<String>? = null
    var callBack: ((Boolean) -> Unit)? = null

    fun removeFragment() {
        val fragmentTransaction: FragmentTransaction = parentFragmentManager.beginTransaction()
        fragmentTransaction.remove(this).commit()
    }


    override fun onAttach(context: Context) {
        super.onAttach(context)
        requestMultiplePermissionsLauncher =
            registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { it ->
                //通过的权限
                val grantedList = it.filterValues { it }.mapNotNull { it.key }
                //是否所有权限都通过
                val allGranted = grantedList.size == it.size
                val list = (it - grantedList.toSet()).map { it.key }
                //未通过的权限
                val deniedList =
                    list.filter { ActivityCompat.shouldShowRequestPermissionRationale(requireActivity(), it) }
                //拒绝并且点了“不再询问”权限
                val alwaysDeniedList = list - deniedList.toSet()
                callBack?.invoke(allGranted)
                removeFragment()
            }
        if (permissions?.isNotEmpty() == true)
            requestMultiplePermissionsLauncher.launch(permissions)
    }
}
